﻿using Microsoft.International.Converters.PinYinConverter;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Mangox.Common.Utils
{
    /// <summary>
    /// 汉字转拼音（姓名转拼音）
    /// https://blog.csdn.net/jiemoxiangcha/article/details/81482074
    /// 方案：
    /// Npinyin(可在Nuget安装)+微软PinYinConverter(可在网上下载ChnCharInfo.dll) +自己维护的个别汉字文件（多音字姓氏）
    /// 其实这两个dll 任何一个都可以实现汉字转拼音，然而 NPinyin.dll 收录的汉字并不全，但是很人性化，能识别一些常用的汉字。
    /// 微软的很全但是不人性化。另外本套代码外有一个自己维护的个别汉字文件，例如一些多音字姓氏。
    ///
    ///本程序的使用场景是姓名转拼音，所以先判断第一个汉字是否在自己维护的拼音库中存在，
    ///如果存在者优先使用这个库中汉字所对应的拼音，
    ///如果不存在者优先使用NPinyin库中转化拼音的方法，转化失败再使用微软提供的ChnCharInfo中转拼音的方法。
    ///接下来是本程序维护的 PinYinDic.txt，该文件放在"\bin\Debug"目录下，当然也可以不使用。
    /// </summary>
    public class PinYinHelper2
    {
        private static Encoding gb2312 = Encoding.GetEncoding("GB2312");
        /// <summary>
        /// 汉字转全拼
        /// </summary>
        /// <param name="strChinese"></param>
        /// <param name="pinyinDic"></param>
        /// <returns></returns>
        public static string ConvertToAllSpell(string strChinese, IDictionary<char, string> pinyinDic = null)
        {
            try
            {
                if (strChinese.Length != 0)
                {
                    StringBuilder fullSpell = new StringBuilder();
                    for (int i = 0; i < strChinese.Length; i++)
                    {
                        var chr = strChinese[i];
                        string pinyin = string.Empty;
                        pinyin = GetFromPinYinDic(chr, pinyinDic);
                        if (pinyin.Length == 0)
                        {
                            pinyin = GetSpell(chr);
                        }
                        //首字母大写
                        pinyin = pinyin.Substring(0, 1).ToUpper() + pinyin.Substring(1);
                        fullSpell.Append(pinyin);
                    }

                    return fullSpell.ToString().ToLower();
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("全拼转化出错！" + e.Message);
            }

            return string.Empty;
        }

        /// <summary>
        /// 汉字转首字母
        /// </summary>
        /// <param name="strChinese"></param>
        /// <param name="pinyinDic"></param>
        /// <returns></returns>
        public static string GetFirstSpell(string strChinese, IDictionary<char, string> pinyinDic = null)
        {
            try
            {
                if (strChinese.Length != 0)
                {
                    StringBuilder fullSpell = new StringBuilder();
                    for (int i = 0; i < strChinese.Length; i++)
                    {
                        var chr = strChinese[i];

                        string pinyin = string.Empty;
                        pinyin = GetFromPinYinDic(chr, pinyinDic);
                        if (pinyin.Length == 0)
                        {
                            pinyin = GetSpell(chr);
                        }

                        char[] chars = pinyin.ToCharArray(); //字符串转Char[]

                        fullSpell.Append(pinyin[0]); //GetSpell(chr)[0]
                    }

                    return fullSpell.ToString().ToUpper();
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("首字母转化出错！" + e.Message);
            }

            return string.Empty;
        }

        private static string GetSpell(char chr)
        {
            var coverchr = NPinyin.Pinyin.GetPinyin(chr);
            bool isChineses = ChineseChar.IsValidChar(coverchr[0]);
            if (isChineses)
            {
                ChineseChar chineseChar = new ChineseChar(coverchr[0]);
                foreach (string value in chineseChar.Pinyins)
                {
                    if (!string.IsNullOrEmpty(value))
                    {
                        return value.Remove(value.Length - 1, 1);
                    }
                }
            }

            return coverchr;
        }

        /// <summary>
        /// 从字典获取拼音
        /// </summary>
        /// <param name="c">字</param>
        /// <param name="pinyinDic">字典</param>
        /// <returns></returns>
        private static string GetFromPinYinDic(char c, IDictionary<char, string> pinyinDic)
        {
            if (pinyinDic == null
            || pinyinDic.Count == 0
            || !pinyinDic.ContainsKey(c))
            {
                return "";
            }

            return pinyinDic[c];
        }

        /// <summary>
        /// 从字典获取拼音，重载
        /// </summary>
        /// <param name="c">字</param>
        /// <param name="pinyinDic">字典</param>
        /// <returns></returns>
        private static string GetFromPinYinDic(string c, IDictionary<string, string> pinyinDic)
        {
            if (pinyinDic == null
            || pinyinDic.Count == 0
            || !pinyinDic.ContainsKey(c))
            {
                return "";
            }

            return pinyinDic[c];
        }
    }

}


//放入text
//{
//"红":"hong",
//"贾":"jia",
//"薄":"bo",
//"褚":"chu",
//"翟":"zhai",
//"郇":"xun",
//"盖":"ge",
//"乐":"yue",
//"区":"ou",
//"卜":"bu",
//"曾":"zeng",
//"丁":"ding",
//"无":"wu",
//"长":"chang",
//"其":"qi",
//"巷":"xiang",
//"将":"jiang",
//"氏":"shi",
//"色":"se",
//"系":"xi",
//"重":"chong",
//"乜":"nie",
//"孛":"bo",
//"卒":"zu",
//"单":"shan",
//"解":"xie",
//"仇":"qiu",
//"隗":"wei",
//"查":"zha",
//"繁":"po",
//"朴":"piao",
//"行":"Hang"
//}

/// <summary>
/// 汉字转拼音，示例调用
/// 方案： //Npinyin+微软PinYinConverter +自己维护的个别汉字文件（多音字姓氏）
/// </summary>
//private static string GetPinYin()
//{
//    //获取全拼
//    string path = @"PinYinDic.txt"; //本程序维护的 PinYinDic.txt，该文件放在"\bin\Debug"目录下，当然也可以不使用。
//    StreamReader sr = new StreamReader(path, Encoding.Default);
//    Dictionary<char, string> pinyinDic = JsonConvert.DeserializeObject<Dictionary<char, string>>(sr.ReadToEnd());

//    string name1 = "赣锋锂业"; //
//    Console.WriteLine(name1 + PinYinHelper2.ConvertToAllSpell(name1, pinyinDic));
//    Console.WriteLine(name1 + PinYinHelper2.GetFirstSpell(name1, pinyinDic));
//}